//
//  ChangeColorView.m
//  carcareIOS
//
//  Created by wr on 16/4/6.
//  Copyright © 2016年 chezheng. All rights reserved.
//

#import "ChangeColorView.h"
@interface ChangeColorView()
@property (nonatomic) CGPoint startPoint;
@property (nonatomic) CGPoint endPoint;
@property (nonatomic) UIColor * startColor;
@property (nonatomic) UIColor * endColor;
@end
@implementation ChangeColorView

- (instancetype)initWithFrame:(CGRect)frame withStartColor:(UIColor *)startColor withEndColor:(UIColor *)endColor withStartPoint:(CGPoint)startPoint withEndPoint:(CGPoint)endPoint
{
    self = [super initWithFrame:frame];
    
    if (self) {
        self.startPoint = startPoint;
        self.endPoint = endPoint;
        self.startColor = startColor;
        self.endColor = endColor;
        
    }
    return self;
}
- (void)setUpStartColor:(UIColor *)startColor withEndColor:(UIColor *)endColor
{
    self.startColor = startColor;
    self.endColor = endColor;
    [self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 绘制颜色渐变
    // 创建色彩空间对象
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    // 创建起点颜色
    CGColorRef beginColor = self.startColor.CGColor;
    // 创建终点颜色
    CGColorRef endColor = self.endColor.CGColor;
    // 创建颜色数组
    CFArrayRef colorArray = CFArrayCreate(kCFAllocatorDefault, (const void*[]){beginColor, endColor}, 2, nil);
    // 创建渐变对象
    CGGradientRef gradientRef = CGGradientCreateWithColors(colorSpaceRef, colorArray, (CGFloat[]){
        0.0f,	   // 对应起点颜色位置
        1.0f		// 对应终点颜色位置
    });
    // 释放颜色数组
//    CFRelease(colorArray);
//    // 释放起点和终点颜色
//    CGColorRelease(beginColor);
//    CGColorRelease(endColor);
    // 释放色彩空间
//    CGColorSpaceRelease(colorSpaceRef);
    CGContextDrawLinearGradient(context, gradientRef, CGPointMake(self.startPoint.x, self.startPoint.y), CGPointMake(self.endPoint.x, self.endPoint.y), 0);
    // 释放渐变对象
//    CGGradientRelease(gradientRef);
}
@end
